/**
 * @description [ axios 请求封装]
 */
import axios, { AxiosResponse, AxiosRequestConfig } from 'axios'
import { Dialog, Toast } from 'vant'
 import store from '@/store'
 import router from '@/router'
// 根据环境不同引入不同api地址
 import { config } from '@/config'

 const service = axios.create({
   baseURL:config.baseApi, //目前使用本地mock，若开启proxy代理url：config.baseApi + '/api'
   timeout:5000,
   withCredentials:false
 })

 // request interceptors
 service.interceptors.request.use((config: AxiosRequestConfig)=>{
    //加载动画
    if(config.loading){
      Toast.loading({message:'加载中...',forbidClick:true,loadingType: 'spinner'})
    }
    //在此次添加请求头等信息，如添加token
    // if(store.state.token){
    //   config.headers['Authorization'] = `${store.state.token}`
    // }
    return config
 },(error: any) => {
   Promise.reject(error)
 })

 //response interceptors
 service.interceptors.response.use(async (response: AxiosResponse) =>{
   Toast.clear();
   const res = response.data;
   if(res.code !== 0){
     //token过期
     if(res.code === 401){
       //警告提示框
       return
     }else if(res.code === 403){
       Dialog.alert({
         title:'警告',
         message:res.msg
       })
       return
     }
      //若后台返回错误值，此处返回对应错误对象，下面error就会接收
      return Promise.reject(new Error(res.msg || 'Error'))
   }else {
     return response.data
   }
 },(error:any) => {
   Toast.clear();
   if(error && error.response){
    switch(error.response.status){
      case 400:
        error.message = '请求错误(400)'
        break
      case 401:
        error.message = '未授权，请登录(401)'
        break
      case 403:
        error.message = '拒绝访问(403)'
        break
      case 404:
        error.message = `请求地址出错:${error.response.config.url}`
        break
      case 500:
        error.message = '服务器内部错误(500)'
        break
      case 504:
        error.message = '网络超时(504)'
        break
      default:
        error.message = `连接错误，${error.message}`
    }
   }else {
     if(error.message == 'Network Error'){
       error.message = '网络异常，请检查后重试'
     }
        error.message = '连接到服务器失败，请联系管理员'
   }
    Toast(error.message)
    //store.dispatch('clearAuth') //清空授权信息
    return Promise.reject(error)
 })

 export default service